#!/bin/sh

set -e

# shellcheck disable=SC1091
[ -f /etc/default/alloy ] && . /etc/default/alloy

# Initial installation: $1 == configure
# Upgrade: $1 == configure, $2 == old version
case "$1" in
    configure)
        [ -z "$ALLOY_USER" ] && ALLOY_USER="alloy"
        [ -z "$ALLOY_GROUP" ] && ALLOY_GROUP="alloy"
        if ! getent group "$ALLOY_GROUP" > /dev/null 2>&1 ; then
            groupadd -r "$ALLOY_GROUP"
        fi
        if ! getent passwd "$ALLOY_USER" > /dev/null 2>&1 ; then
            useradd -m -r -g "$ALLOY_GROUP" -d /var/lib/alloy -s /sbin/nologin -c "alloy user" "$ALLOY_USER"
        fi

        # Add Alloy user to groups used for reading logs.
        if getent group adm > /dev/null 2>&1 ; then
            usermod -a -G adm "$ALLOY_USER"
        fi
        if getent group systemd-journal > /dev/null 2>&1 ; then
            usermod -a -G systemd-journal "$ALLOY_USER"
        fi

        if [ ! -d /var/lib/alloy ]; then
          mkdir /var/lib/alloy
          chown "$ALLOY_USER":"$ALLOY_GROUP" /var/lib/alloy
          chmod 770 /var/lib/alloy
        fi

        if [ ! -d /var/lib/alloy/data ]; then
          mkdir /var/lib/alloy/data
          chown "$ALLOY_USER":"$ALLOY_GROUP" /var/lib/alloy/data
          chmod 770 /var/lib/alloy/data
        fi

        chown root:"$ALLOY_GROUP" /etc/alloy
        chmod 770 /etc/alloy

        if [ -z ${2+x} ] && [ "$RESTART_ON_UPGRADE" = "true" ]; then
            if command -v systemctl 2>/dev/null; then
                systemctl daemon-reload
                systemctl restart alloy
            fi
        fi
esac
